/*
 * @Description:
 * @Author: Cxy
 * @Date: 2023-04-13 15:11:55
 * @LastEditors: Cxy
 * @LastEditTime: 2024-02-28 10:48:14
 * @FilePath: \blogAdmin\play\src\components\XyIcon\src\index.tsx
 */
import { Icon, addIcon } from '@iconify/vue'
import svgData from 'assets/svg'
import { iconifyData } from './data'
import type { Ref } from 'vue'

type SvgDataInter = {
  [K in string]: () => Promise<Component>
}

type iconConfigInter = Ref<{
  dom: any
  type: string
  asyncLoad: boolean
  icon: string
}>

export default defineComponent({
  name: 'XyIcon',
  components: { Icon },
  props: {
    icon: {
      type: String,
      default: 'ep/info-filled'
    }
  },
  setup(props) {
    const iconConfig: iconConfigInter = ref({
      dom: markRaw({}),
      type: '',
      asyncLoad: false,
      icon: ''
    })
    watch(
      () => props.icon,
      async icon => {
        iconConfig.value.icon = icon.replace(/\//g, ':')
        /* iconify本地图标加载 */
        if (Object.keys(iconifyData).includes(iconConfig.value.icon)) {
          const data = await iconifyData[iconConfig.value.icon]()
          iconConfig.value.dom = data.default
          iconConfig.value.type = 'iconify'
        }
        /* svg本地图标加载 */
        if (Object.keys(svgData).includes(icon)) {
          const data = await (svgData as SvgDataInter)[icon]()
          iconConfig.value.dom = data
          iconConfig.value.type = 'svg'
        }
        iconConfig.value.asyncLoad = true
      },
      {
        immediate: true
      }
    )
    return {
      iconConfig
    }
  },
  render() {
    const {
      $attrs: attrs,
      iconConfig: { type, dom, icon }
    } = this
    /* iconify 本地图标加载 */
    if (type === 'iconify') {
      addIcon(icon, dom)
      return h(Icon, {
        icon,
        style: attrs?.style ? Object.assign(attrs.style, { outline: 'none' }) : { outline: 'none' },
        ...attrs
      })
    }
    /* svg 本地图标加载 */
    if (type === 'svg') {
      return h(dom, {
        'aria-hidden': 'true',
        width: '1em',
        height: '1em',
        style: attrs?.style ? Object.assign(attrs.style, { outline: 'none' }) : { outline: 'none' },
        ...attrs
      })
    }
    /* iconify 线上图标加载 https://icones.js.org/ */
    return h(Icon, {
      icon,
      style: attrs?.style ? Object.assign(attrs.style, { outline: 'none' }) : { outline: 'none' },
      ...attrs
    })
  }
})
